<?php
$training_id = $_GET['id'] ?? 0;
if ($training_id > 0) {
    $pageTitle = "编辑培训";
} else {
    $pageTitle = "添加培训";
}
include("header.php");

// 初始化错误信息变量
$error = '';
$success = '';

/**
 * @var PDO $pdo
 * 创建培训信息表（如果不存在，内容包括：主办科室	培训主题	培训开始时间	培训结束时间	培训地点	培训人数	培训费用	其他费用	其它说明	培训内容）
 *   $pdo->exec("CREATE TABLE IF NOT EXISTS trainings (
 *   id INTEGER PRIMARY KEY AUTOINCREMENT,
 *   department TEXT NOT NULL,
 *   title TEXT NOT NULL,
 *   start_time date NOT NULL,
 *   end_time date NOT NULL,
 *   location TEXT NOT NULL,
 *   type TEXT NOT NULL,
 *   content TEXT,
 *   created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
 */

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $training_id = $_POST['id'] ?? 0;
    $department = $_POST['department'] ?? '';
    $title = $_POST['title'] ?? '';
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $location = $_POST['location'] ?? '';
    $type = $_POST['type'] ?? '';
    $content = $_POST['content'] ?? '';

    // 验证所有输入是否为空
    $requiredFields = ['department', 'title', 'start_date', 'end_date', 'location', 'type'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $error = '所有字段都是必填的';
            break;
        }
    }
    if ($error != '') {
    } elseif (strtotime($end_date) < strtotime($start_date)) {
        $error = '结束日期必须在开始日期之后';
    } else {
        if ($training_id == 0) {
            // 插入新培训信息
            $stmt = $pdo->prepare('INSERT INTO trainings (department, title, start_time, end_time, location, type, content) VALUES (?, ?, ?, ?, ?, ?, ?)');
            if ($stmt->execute([$department, $title, $start_date, $end_date, $location, $type, $content])) {
                $success = '培训信息添加成功';
                header('Location: index.php');
                exit();
            } else {
                $error = '培训信息添加失败';
            }
        } else {
            // 更新培训信息
            $stmt = $pdo->prepare('UPDATE trainings SET department = ?, title = ?, start_time = ?, end_time = ?, location = ?, type = ?, content = ? WHERE id = ?');
            if ($stmt->execute([$department, $title, $start_date, $end_date, $location, $type, $content, $training_id])) {
                $success = '培训信息更新成功';
                header('Location: index.php');
                exit();
            } else {
                $error = '培训信息更新失败';
            }
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && $training_id > 0) {
    $stmt = $pdo->prepare('SELECT * FROM trainings WHERE id = ?');
    if ($stmt->execute([$training_id])) {
        $training = $stmt->fetch(PDO::FETCH_ASSOC);
        $department = $training['department'];
        $title = $training['title'];
        $start_date = $training['start_time'];
        $end_date = $training['end_time'];
        $location = $training['location'];
        $type = $training['type'];
        $content = $training['content'];
    }
}
?>
<div class="row">
    <div class="card login-card">
        <div class="card-body">
            <h2 class="card-title text-center mb-4"><?= $training_id > 0 ? '编辑培训' : '添加培训' ?></h2>

            <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
            <?php endif; ?>

            <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
                <input type="hidden" name="id" value="<?= htmlspecialchars($training_id ?? '') ?>">
                <div class="mb-3">
                    <label for="title">主办科室或学校：</label>
                    <input type="text" class="form-control" id="department" name="department"
                        value="<?= htmlspecialchars($department ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="title">培训主题：</label>
                    <input type="text" class="form-control" id="title" name="title"
                        value="<?= htmlspecialchars($title ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="start_date">开始日期：</label>
                    <input placeholder="请选择日期" type="date" class="form-control" id="start_date" name="start_date"
                        value="<?= htmlspecialchars($start_date ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="end_date">结束日期：</label>
                    <input placeholder="请选择日期" type="date" class="form-control" id="end_date" name="end_date"
                        value="<?= htmlspecialchars($end_date ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="location">培训地点：</label>
                    <input type="text" class="form-control" id="location" name="location"
                        value="<?= htmlspecialchars($location ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="type">任务或自主：</label>
                    <input type="text" class="form-control" id="type" name="type"
                        value="<?= htmlspecialchars($type ?? '') ?>" required>
                </div>

                <div class="mb-3">
                    <label for="content">培训内容：</label>
                    <textarea class="form-control" id="content" name="content" rows="5"
                        ><?= htmlspecialchars($content ?? '') ?></textarea>
                </div>

                <button type="submit" class="btn btn-primary">提交</button>
                <a href="index.php" class="btn btn-secondary">取消</a>
            </form>
        </div>
    </div>
</div>
<!-- 引入脚本 -->
<?php include("footer.php"); ?>
<script type="text/javascript">
    $(document).ready(function () {
        $('#start_date').datepicker({
            format: "yyyy-mm-dd",
            language: "zh-CN",
            autoclose: true,
            todayHighlight: true
        });
        $('#end_date').datepicker({
            format: "yyyy-mm-dd",
            language: "zh-CN",
            autoclose: true,
            todayHighlight: true
        });
    });
</script>